package de.gwtprime.server.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import de.gwtprime.server.sql.HibernateEntityMangerSingelton;
import de.gwtprime.server.util.MailSender;
import de.gwtprime.shared.Stock;
import de.gwtprime.shared.TradingPosition;
import de.gwtprime.util.Helper;


/**
 * Servlet runs every day and sends out an e-mail if position should be opend/closed
 * @author jan
 *
 */
public class MailSenderServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	private static Logger logger = Logger.getLogger(MailSenderServlet.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		logger.info("Running Mail sender servlet");
		List<Stock> list = new ArrayList<Stock>();
		try {
			//list = new StockAnalyzer2().analyzeStock("DAX");
		} catch (Exception e) {
			logger.error("Could not analyze index", e);
		}

		List<TradingPosition> tradingPositions = list.get(0).getTradeResult().getPositions();
		
		Collections.sort(tradingPositions);

		TradingPosition p = null;
		if(tradingPositions.size()>0){
			p = tradingPositions.get(tradingPositions.size()-1);


			boolean today = false;
			Calendar cal2 = Calendar.getInstance();
			cal2.setTime(p.getOpenDate());
			if(Helper.compareDates(Calendar.getInstance(), cal2)==0){
				today=true;
				
			}
			resp.getWriter().write("today: "+cal2+"<br>");
			
			
			String openPosition = "Open position now ("+p.getOpenDate()+") for "+p.getOpenValue();
			String closePosition = "Close position now ("+p.getCloseDate()+") for "+p.getCloseValue();
			MailSender.sendMailToAdmin("Buy now +"+ p.getOpenDate()+ (today ? "TODAY" : "NOT TODAY"), openPosition + closePosition);
		}else{
			MailSender.sendMailToAdmin("error", "error");
		}
		resp.getWriter().write("mail sent"+p.getOpenDate()+"...");


	}

	

}
